﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Common.Net.Utilities
{
    public static class ExpressionFormatter
    {
        public static string Format<T>(Expression<Func<T>> expression)
        {
            return Format(expression.Body);
        }

        public static string Format(Expression body)
        {
            if (body is MemberExpression)
            {
                var memberExpr = (MemberExpression)body;

                if (memberExpr.Expression == null)
                    return string.Format("{0}.{1}", memberExpr.Member.DeclaringType.Name, memberExpr.Member.Name);
                else
                {
                    if (memberExpr.Expression is ConstantExpression)
                        return memberExpr.Member.Name;
                    else
                    {
                        var formattedExpr = Format(memberExpr.Expression);
                        return string.Format("{0}.{1}", formattedExpr, memberExpr.Member.Name);
                    }
                }
            }
            else
                return body.ToString();
        }
    }
}
